package com.mylife.bill.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mylife.bill.vo.AccountInformationVo;
import com.mylife.bill.vo.BillVO;
import com.mylife.bill.vo.DifNecessityCostVO;
import com.mylife.bill.vo.DifTypeCostVO;
import com.mylife.pojo.PageDataInfo;
import com.mylife.pojo.Result;
import com.mylife.bill.mapper.BillMapper;
import com.mylife.bill.service.BillService;
import com.mylife.bill.vo.params.BillParams;
import com.mylife.pojo.TransferUtils;
import com.mylife.service.HttpStatus;
import com.mylife.service.ReturnCodes;
import com.mylife.service.ReturnMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * @author blueCat
 * @since 2022/2/24
 */
@Service
public class BillServiceImpl implements BillService {

    @Autowired
    private BillMapper billmapper;

    /**
     * 添加账单
     *
     * @param params
     * @return
     */
    @Override
    public Result addBill(BillParams params) {
        //转换重要性
        switch (params.getNecessityStr()) {
            case "必要":
                params.setNecessity(1);
                break;
            case "可以不花":
                params.setNecessity(2);
                break;
            case "完全没必要":
                params.setNecessity(0);
                break;
        }
        int i = billmapper.addBill(params);
        if (i == 1) {
            //扣除相应账户金额
            params.setAccountBalance(0 - params.getConsumptionAmount());
            int deductExpense = billmapper.updateAccountInformation(params);
            return Result.setSuccess(HttpStatus.SUCCESS, "添加账单成功！");
        } else {
            return Result.setFail(ReturnCodes.ADD_BILL_FAIL, ReturnMessage.ADD_BILL_FAIL);
        }
    }

    /**
     * 查询全部消费类型
     *
     * @return
     */
    @Override
    public List<String> queryConsumptionType() {
        return billmapper.queryConsumptionType();
    }

    /**
     * 根据消费类型查询全部消费内容
     *
     * @param consumptionType
     * @return
     */
    @Override
    public List<String> queryConsumptionContent(String consumptionType) {
        return billmapper.queryConsumptionContent(consumptionType);
    }

    /**
     * 查询账单
     *
     * @param params
     * @return
     */
    @Override
    public Result queryBills(BillParams params) {
        //转换重要性
        switch (params.getNecessityStr()) {
            case "必要":
                params.setNecessity(1);
                break;
            case "可以不花":
                params.setNecessity(2);
                break;
            case "完全没必要":
                params.setNecessity(0);
                break;
        }
        //处理timeRange获得startTime和endTime
        if (params.getTimeRange() != null && params.getTimeRange().size() > 0) {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(1) + " 23:59:59");
        }
        Page<BillVO> page = new Page<>(params.getPageNum(), params.getPageSize());
        List<BillVO> billVOS = billmapper.queryBills(page, params);
        //回填重要性和单位和序号
        int index = (int) ((params.getPageNum() - 1) * params.getPageSize()) + 1;
        for (BillVO billVO : billVOS) {
            billVO.setIndex(index++);
            switch (billVO.getNecessity()) {
                case 1:
                    billVO.setNecessityStr("必要");
                    break;
                case 2:
                    billVO.setNecessityStr("可以不花");
                    break;
                case 0:
                    billVO.setNecessityStr("完全没必要");
                    break;
            }
            billVO.setConsumptionAmountStr(String.format("%.2f", billVO.getConsumptionAmount()) + "元");
        }
        return Result.setSuccess(HttpStatus.SUCCESS, "", new PageDataInfo(page, billVOS));
    }

    /**
     * 查询当天消费总额
     *
     * @param params
     * @return
     */
    @Override
    public String queryConsumptionAmount(BillParams params) {
        //转化重要性
        if (params.getNecessityStr() != null && params.getNecessityStr() != "") {
            params.setNecessity(TransferUtils.transferNecessity(params.getNecessityStr()));
        }
        //处理timeRange获得startTime和endTime
        if (params.getTimeRange() != null && params.getTimeRange().size() > 1) {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(1) + " 23:59:59");
        } else if (params.getTimeRange() != null && params.getTimeRange().size() == 1) {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(0) + " 23:59:59");
        }
        String consumptionAmount = billmapper.queryConsumptionAmount(params);
        if (consumptionAmount == null || consumptionAmount == "null") {
            consumptionAmount = "0";
        }
        return consumptionAmount + "元";
    }

    /**
     * 新增记账类型
     *
     * @param params
     * @return
     */
    @Override
    public Result addBillType(BillParams params) {
        //获取该类型已存在数目
        Integer typeNumber = billmapper.checkBillType(params.getConsumptionType());
        if (params.getConsumptionContent() == null || params.getConsumptionContent() == "") {
            //内容为空的情况下，不允许插入已存在的类型
            if (typeNumber > 0) {
                return Result.setFail(ReturnCodes.BILL_TYPE_EXIST, ReturnMessage.BILL_TYPE_EXIST);
            }
        }
        //验证内容是否存在
        Integer contentNumber = billmapper.checkBillContent(params.getConsumptionContent());
        if (contentNumber > 0) {
            return Result.setFail(ReturnCodes.BILL_CONTENT_EXIST, ReturnMessage.BILL_CONTENT_EXIST);
        }
        //插入类型,只有当该类型不存在时才执行插入
        if (typeNumber == 0) {
            billmapper.insertBillType(params.getConsumptionType());
        }
        //插入内容
        billmapper.insertBillContent(params.getConsumptionContent(), params.getConsumptionType());
        return Result.setSuccess(HttpStatus.SUCCESS, "添加成功！");
    }

    /**
     * 删除帐单
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteBill(Integer id) {
        BillVO billVO = billmapper.queryOneBill(id);
        Integer number = billmapper.deleteBill(id);
        if (number == 1) {
            //修改账户金额
            BillParams params = new BillParams();
            params.setAccountType(billVO.getAccountType());
            params.setUsername(billVO.getUsername());
            params.setAccountBalance(billVO.getConsumptionAmount());
            billmapper.updateAccountInformation(params);
            return Result.setSuccess(HttpStatus.SUCCESS, "删除成功！");
        } else {
            return Result.setFail(ReturnCodes.BILL_DELETE_FAIL, ReturnMessage.BILL_DELETE_FAIL);
        }
    }

    /**
     * 查询单条账单
     *
     * @param id
     * @return
     */
    @Override
    public BillVO queryOneBill(Integer id) {
        BillVO billVO = billmapper.queryOneBill(id);
        if (billVO.getNecessity() != null) {
            switch (billVO.getNecessity()) {
                case 1:
                    billVO.setNecessityStr("必要");
                    break;
                case 2:
                    billVO.setNecessityStr("可以不花");
                    break;
                case 0:
                    billVO.setNecessityStr("完全没必要");
                    break;
            }
        }
        return billVO;
    }

    /**
     * 修改单条账单
     *
     * @param params
     * @return
     */
    @Override
    public Result updateBill(BillParams params) {
        //处理createTime
        if (params.getCreateTime() != null && params.getCreateTime() != "") {
            params.setCreateTime(params.getCreateTime().substring(0, 10) + " 00:00:00");
        }
        //处理重要性
        switch (params.getNecessityStr()) {
            case "必要":
                params.setNecessity(1);
                break;
            case "可以不花":
                params.setNecessity(2);
                break;
            case "完全没必要":
                params.setNecessity(0);
                break;
        }
        //查询修改之前的消费额
        BillVO billVO = billmapper.queryOneBill(params.getId());
        Double consumptionAmount = billVO.getConsumptionAmount();
        //获得两个消费额的差值
        Double difValue = consumptionAmount - params.getConsumptionAmount();
        Integer number = billmapper.updateBill(params);
        if (number == 1) {
            if (difValue != 0){
                //修改账户信息
                params.setAccountBalance(difValue);
                billmapper.updateAccountInformation(params);
            }
            return Result.setSuccess(HttpStatus.SUCCESS, "修改成功！");
        } else {
            return Result.setFail(ReturnCodes.BILL_UPDATE_FAIL, ReturnMessage.BILL_UPDATE_FAIL);
        }
    }

    /**
     * 查询不同重要性消费
     *
     * @param params
     * @return
     */
    @Override
    public List<DifNecessityCostVO> queryDifNecessityCost(BillParams params) {
        //处理timeRange获得startTime和endTime
        if (params.getTimeRange() != null && params.getTimeRange().size() > 1) {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(1) + " 23:59:59");
        } else {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(0) + " 23:59:59");
        }
        List<DifNecessityCostVO> difNecessityCostVOS = billmapper.queryDifNecessityCost(params);
        for (DifNecessityCostVO difNecessityCostVO : difNecessityCostVOS) {
            difNecessityCostVO.setConsumptionAmount(difNecessityCostVO.getConsumptionAmount() + "元");
        }
        return difNecessityCostVOS;
    }

    /**
     * 查询不同消费类型消费
     *
     * @param params
     * @return
     */
    @Override
    public List<DifTypeCostVO> queryDifTypeCost(BillParams params) {
        //处理timeRange获得startTime和endTime
        if (params.getTimeRange() != null && params.getTimeRange().size() > 1) {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(1) + " 23:59:59");
        } else {
            List<String> timeRange = params.getTimeRange();
            params.setStartTime(timeRange.get(0) + " 00:00:00");
            params.setEndTime(timeRange.get(0) + " 23:59:59");
        }
        List<DifTypeCostVO> difNecessityCostVOS = billmapper.queryDifTypeCost(params);
        for (DifTypeCostVO difNecessityCostVO : difNecessityCostVOS) {
            difNecessityCostVO.setConsumptionAmount(difNecessityCostVO.getConsumptionAmount() + "元");
            params.setConsumptionType(difNecessityCostVO.getConsumptionType());
            List<String> cost = billmapper.queryDifTypeNecessity(params);
            difNecessityCostVO.setNecessity_1(cost.get(0) + "元");
            difNecessityCostVO.setNecessity_2(cost.get(1) + "元");
            difNecessityCostVO.setNecessity_3(cost.get(2) + "元");
        }
        return difNecessityCostVOS;
    }

    /**
     * 查询全部账户类型
     *
     * @return
     */
    @Override
    public List<String> queryAccountType() {
        return billmapper.queryAccountType();
    }

    /**
     * 改变账户信息
     *
     * @param params
     * @return
     */
    @Override
    public Result changeAccountInformation(BillParams params) {
        //判断是新增还是修改
        Integer number = billmapper.accountTypeNum(params.getAccountType(),params.getUsername());
        if (number.equals(0)) {
            //执行新增
            Integer num = billmapper.addAccountInformation(params);
            if (num.equals(1)) {
                return Result.setSuccess(HttpStatus.SUCCESS, "新增账户信息成功！");
            } else {
                return Result.setFail(ReturnCodes.ADD_ACCOUNT_INFORMATION_FAIL, ReturnMessage.ADD_ACCOUNT_INFORMATION_FAIL);
            }
        } else {
            //执行修改
            if (params.getAccountBalance() == null) {
                params.setAccountBalance(0.00);
            }
            Integer num = billmapper.updateAccountInformation(params);
            if (num.equals(1)) {
                return Result.setSuccess(HttpStatus.SUCCESS, "修改账户信息成功！");
            } else {
                return Result.setFail(ReturnCodes.UPDATE_ACCOUNT_INFORMATION_FAIL, ReturnMessage.UPDATE_ACCOUNT_INFORMATION_FAIL);
            }
        }
    }

    /**
     * 查询全部账户信息
     *
     * @param username
     * @return
     */
    @Override
    public List<AccountInformationVo> queryAccountInformation(String username) {
        List<AccountInformationVo> data = billmapper.queryAccountInformation(username);
        //回填序号并计算总额
        double sumBalance = 0;
        int index = 1;
        //设置格式
        DecimalFormat df = new DecimalFormat("0.00");
        for (AccountInformationVo datum : data) {
            datum.setIndex(index++);
            sumBalance += datum.getAccountBalance();
        }
        if (data.size() > 0) {
            data.get(0).setSumBalance(Double.parseDouble(df.format(sumBalance)));
        }
        return data;
    }

    /**
     * 删除账户信息
     * @param id
     * @return
     */
    @Override
    public Result deleteAccount(Integer id) {
        Integer number = billmapper.deleteAccount(id);
        if (number == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "删除成功！");
        } else {
            return Result.setFail(ReturnCodes.DELETE_ACCOUNT_INFORMATION_FAIL, ReturnMessage.DELETE_ACCOUNT_INFORMATION_FAIL);
        }
    }
}
